const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const mongoose = require('../db')
const koajwt = require('koa-jwt')
const {SECRET} = require('../config/config')
const errHandler = require("./errHandler")
// const index = require('../routes')
// const users = require('../routes/users')
// const upload = require('../routes/upload')

const router = require("../routes")
// error handler
onerror(app)
mongoose()
// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))
app.use(async (ctx, next) => {
  return await next().catch((err) => {
      if (err.status === 401) {
          ctx.status = 401;
          ctx.body = {
              code: 401,
              msg: '认证过期'
          }
      } else if (err.status === 404){
          ctx.status = 404;
          ctx.body = {
              code: 404,
              msg: '未检测接口'
          }
      }  else {
          throw err;
      }
  })
});
app.use(koajwt({
  secret:SECRET,
}).unless({
  path:[
    /^\/users\/login/,
    /^\/users\/register/,
  ]
}))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// routes
// app.use(index.routes())
// app.use(users.routes())
// app.use(upload.routes())
app.use(router.routes())
// error-handling错误处理
app.on('error', errHandler);

module.exports = app
